<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="title">医院陪护系统-患者端</div>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userType">
          <el-radio-group v-model="loginForm.userType">
            <el-radio :label="1">患者</el-radio>
            <el-radio :label="2">护工</el-radio>
            <el-radio :label="3">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-button" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
      <div style="text-align: center; margin-top: 16px">
      <el-button type="text" @click="registerDialogVisible = true">没有账号？注册</el-button>
    </div>
    </el-card>

    <el-dialog v-model="registerDialogVisible" title="注册" width="400px">
      <el-form
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="registerForm.userType">
            <el-radio :label="1">患者</el-radio>
            <el-radio :label="2">护工</el-radio>
            <el-radio :label="3">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="registerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { listUser, addUser } from '@/api/user'
import { listCaregiver, addCaregiver } from '@/api/caregiver'
import { listAdmin, addAdmin } from '@/api/admin'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const loginFormRef = ref(null)
const loginForm = reactive({
  username: '',
  password: '',
  userType: 1
})

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
}

const registerDialogVisible = ref(false)
const registerFormRef = ref(null)
const registerForm = reactive({
  username: '',
  password: '',
  userType: 1
})
const registerRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
}

const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    let apiFn
    let query
    if (loginForm.userType === 2) {
      // 护工
      query = { name: loginForm.username, password: loginForm.password }
    } else {
      // 患者和管理员
      query = { username: loginForm.username, password: loginForm.password }
    }
    if (loginForm.userType === 1) {
      apiFn = listUser
    } else if (loginForm.userType === 2) {
      apiFn = listCaregiver
    } else if (loginForm.userType === 3) {
      apiFn = listAdmin
    }
    try {
      const res = await apiFn(query)
      if (Array.isArray(res) && res.length > 0) {
        // 登录成功，保存用户信息
        const user = res[0]
        const userInfo = {
          userType: loginForm.userType,
          userId: user.userId || user.adminId || user.caregiverId,
          username: user.username || user.name,
          password: loginForm.password
        }
        
        // 使用 Pinia store 保存用户信息
        userStore.setUserInfo(userInfo)
        
        // 跳转
        const routes = {
          1: '/patient/order',
          2: '/caregiver/apply',
          3: '/admin/statistics'
        }
        router.push(routes[loginForm.userType])
      } else {
        ElMessage.error('用户名或密码错误')
      }
    } catch (e) {
      ElMessage.error('登录失败，请重试')
    }
  })
}

const handleRegister = () => {
  registerFormRef.value.validate(async (valid) => {
    if (!valid) return
    let apiFn
    let data = {
      password: registerForm.password
    }
    // 如果是护工，使用 name 字段，否则使用 username 字段
    if (registerForm.userType === 2) {
      data.name = registerForm.username
    } else {
      data.username = registerForm.username
    }
    if (registerForm.userType === 1) {
      apiFn = addUser
    } else if (registerForm.userType === 2) {
      apiFn = addCaregiver
    } else if (registerForm.userType === 3) {
      apiFn = addAdmin
    }
    try {
      await apiFn(data)
      ElMessage.success('注册成功，请登录')
      // 自动填充登录表单
      loginForm.username = registerForm.username
      loginForm.password = registerForm.password
      loginForm.userType = registerForm.userType
      registerDialogVisible.value = false
    } catch (e) {
      ElMessage.error('注册失败，请重试')
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #e0f2ff 0%, #f5f7fa 100%);
  padding: 20px;
}

.login-card {
  width: 420px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.login-card:hover {
  transform: translateY(-5px);
}

.title {
  font-size: 28px;
  font-weight: bold;
  text-align: center;
  margin: 10px 0 35px;
  background: linear-gradient(45deg, #409eff, #36cf9f);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

:deep(.el-form-item) {
  margin-bottom: 25px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
  margin-top: 10px;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 20px 10px;
  text-align: center;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 30px 25px;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  text-align: center;
}

:deep(.el-button--text) {
  font-size: 14px;
  color: #409eff;
  transition: all 0.3s ease;
}

:deep(.el-button--text:hover) {
  color: #66b1ff;
  transform: translateY(-1px);
}
</style>
